﻿using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YaP.Forms
{
    /// <summary>
    /// This form contains a DataGridView used to list registered channels on current IRC Server.
    /// </summary>
    public partial class GriddedChannelList : Form
    {
        private int nbchannelsField;
        private int NbChannels
        {
            get
            {
                return nbchannelsField;
            }
            set
            {
                nbchannelsField = value;
                Text = "Found " + nbchannelsField + " Channels";
      
            }
        }
        private bool inuseField;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public GriddedChannelList()
        {
            InitializeComponent();
            Text = "Channels List ";
        }

        /// <summary>
        /// Quiet equals to Form.MdiParent, but strongly typped.
        /// </summary>
        public MainForm ParentMainForm
        {
            get { return (MdiParent as MainForm); }
        }

        /// <summary>
        /// Get Or Set. All channel listed in the dataGridView, must match to this regular expression
        /// </summary>
        /// <example>europ* : The DataGridView will contain only channels that begin with "europ"</example>
        /// <remarks>This feature is not implemented yet.</remarks>
        public string FilterExpression { get; set; }

        /// <summary>
        /// Get Or Set. If this Form is in use, the user will not be able to close this Form
        /// </summary>
        public bool InUse
        {
            get { return inuseField; }
            set
            {
                string textToSet = string.Empty;
                if (value)
                {
                    if (!inuseField)
                    {
                        textToSet = Text + " - Fetching List ...";
                    }
                }
                else
                {
                    textToSet = Text + Text.TrimEnd(" - Fetching List ...".ToCharArray());
                }
                if (InvokeRequired)
                {
                    AsyncSetFormText SetTextWithInvoke = SetFormText;
                    BeginInvoke(SetTextWithInvoke, new object[] { textToSet });
                    inuseField = value;
                }
                else
                {
                    SetFormText(textToSet);
                    inuseField = value;
                }
            }
        }

        /// <summary>
        /// Add one channel to the list.
        /// </summary>
        /// <param name="name">Channel name</param>
        /// <param name="count">User count</param>
        /// <param name="topic">Current Topic</param>
        public  void  AddChan(string name, string count, string topic)
        {
            InUse = true;
            //MTA

            
            //STA
            if (InvokeRequired)
            {
                if (dataGridView1 != null)
                    dataGridView1.BeginInvoke(
                        (MethodInvoker)(() => dataGridView1.Rows.Add(new object[] { name, int.Parse(count), topic })));
            }
            else dataGridView1.Rows.Add(new object[] {name, int.Parse(count), topic});
            NbChannels = NbChannels + 1;
        }

        ///<summary>
        /// Better Performance
        ///</summary>
        ///<param name="ChanCollection"></param>
        public void AddChanCollection(List<string[]> ChanCollection)
        {
            InUse = true;
            if (InvokeRequired)
            {
                dataGridView1.BeginInvoke((MethodInvoker)delegate
                                                              {
                                                                  NbChannels = NbChannels + ChanCollection.Count;
                                                                  // dataGridView1.Rows.AddRange(new )
                                                                  foreach (var obj in ChanCollection)
                                                                  {
                                                                      string name = obj[1];
                                                                      string count = obj[2];
                                                                      string topic = obj[3];
                                                                      var add = dataGridView1.Rows.Add(new object[]
                                                                                                           {
                                                                                                               name,
                                                                                                               int.Parse
                                                                                                                   (count)
                                                                                                               ,
                                                                                                               topic
                                                                                                           });
                                                                  }
                                                              })
                    ;
            }
        }
        private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string[] args = new string[2];
            args[0] = dataGridView1.SelectedCells[0].Value.ToString();
            ((MainForm)MdiParent).DoCmd("JOIN", args);
        }

        private void GriddedChannelList_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((InUse) && (e.CloseReason != CloseReason.MdiFormClosing))
            {
                e.Cancel = true;
            }
            else
            {
                ((MainForm)MdiParent).KillChannelList(this);
            }
        }

        private void SetFormText(string text)
        {
            Text = text;
        }

        //Delegate for async invoking

        #region Nested type: AsyncSetFormText

        private delegate void AsyncSetFormText(string _Text);

        #endregion
    }
}